const { getUserByName } = require("../service/user.service");
const md5password = require("../utils/handle-password");
const { createUser } = require("../service/user.service");

class RegisterMiddleware {
  async sendRegister(ctx, next) {
    // 拿到账号密码
    let { name, password, email, tel, role } = ctx.request.body;

    // 判断账号密码是否为空
    if (!name || !password) {
      return ctx.app.emit("error", new Error("账号密码为空"), ctx);
    }

    // 判断账号密码是否注册过
    const res = await getUserByName(name);
    // console.log(res);
    if (res.length >= 1) {
      return (ctx.body = "已经注册过了");
    }

    //密码加密
    password = md5password(password);
    // console.log(password);
    const user = { name, password, email, tel, role };
    // console.log(ctx.request.user);

    // 向数据库插入账号密码
    try {
      const msg = await createUser(user);
      ctx.request.msg = msg;
    } catch {
      return ctx.app.emit("error", new Error("向数据库插入账户失败"), ctx);
    }

    await next();
  }
}

module.exports = new RegisterMiddleware();
